<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'

/**
 * 动态表单的form实例
 */
const dynamicFormRef = ref(null)
const selectOptions = [
  {
    value: 'string',
    label: 'string'
  },
  {
    value: 'innerFunction',
    label: 'innerFunction'
  },
  {
    value: 'customFunction',
    label: 'customFunction'
  },
  {
    value: 'number',
    label: 'number'
  }
]
/**
 * 动态表单绑定的数据
 */
const dynamicFormModel = ref({
  domains: [
    {
      key: 'username',
      value: '@cname',
      type: 'string'
    }
  ]
})

const dynamicFormRules = ref({
  key: [
    {
      required: true,
      message: '请输入key',
      trigger: 'blur'
    }
  ]
})
/**
 * 将表单绑定数据转换为后端配置对象
 */
const dynamicConfig = computed(() => {
  return dynamicFormModel.value.domains.map((domain) => {
    return {
      [domain.key]: domain.value
    }
  })
})

/**
 * 添加新的动态表单数据
 */
const addDomain = async (formEl: FormInstance | undefined, index: number) => {
  if (!formEl) return
  await validateForm(formEl, index)
  dynamicFormModel.value.domains.push({
    key: '',
    value: '',
    type: 'string'
  })
}

const removeDomain = (item) => {
  const index = dynamicFormModel.value.domains.indexOf(item)
  if (index !== -1) {
    dynamicFormModel.value.domains.splice(index, 1)
  }
}
const validateForm = (formEl: FormInstance, index: number) => {
  const key = `domains[${index}].key`
  console.log('key', index)
  return new Promise((resolve) => {
    formEl.validate((isValid: boolean, invalidFields?) => {
      if (isValid) {
        resolve(true)
      } else {
        // console.log('fields', invalidFields)
        ElMessage({
          message: invalidFields[key][0].message || '表单验证失败',
          type: 'error'
        })
      }
    })
  })
}
</script>

<template>
  <div class="mock-container">
    <div class="mock-wrapper">
      <div class="mock-wrapper-item">
        <el-form ref="dynamicFormRef" :model="dynamicFormModel" scroll-to-error>
          <el-form-item
            v-for="(domain, index) in dynamicFormModel.domains"
            :key="index"
            :label="index + 1 + '.请输入'"
          >
            <div :style="{ display: 'flex', flexDirection: 'column' }">
              <el-form-item
                :prop="`domains[${index}].key`"
                :rules="dynamicFormRules.key"
              >
                <el-input
                  v-model="dynamicFormModel.domains[index].key"
                  placeholder="请输入键"
                />
              </el-form-item>
              <el-form-item>
                <el-input v-model="domain.value" placeholder="请输入值" />
              </el-form-item>
              <el-form-item>
                <el-select v-model="domain.type" placeholder="请选择值类型">
                  <el-option
                    v-for="item in selectOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button class="mt-2" @click.prevent="removeDomain(domain)">
                  Delete
                </el-button>
              </el-form-item>
            </div>
          </el-form-item>
          <el-button
            type="primary"
            @click="
              addDomain(dynamicFormRef, dynamicFormModel.domains.length - 1)
            "
            >New domain</el-button
          >
        </el-form>
      </div>
      <div class="mock-wrapper-item">
        <el-card> {{ dynamicConfig }} </el-card>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.mock-container {
  .mock-wrapper {
    display: flex;

    .mock-wrapper-item {
      flex: 1;
    }
  }
}
</style>
